package com.wwz.frame.controller;

import com.wwz.frame.entity.ExceptionInfo;
import com.wwz.frame.exception.GlobalExceptionResolver;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
/**  
* @Description 统一处理错误/异常(针对控制层)
* @Author wwz
* @Date 2019/08/15
* @Param   
* @Return   
*/
@Api(value="GlobalExceptionController",tags = "全局异常处理")
@Controller
@RequestMapping("${server.error.path:/error}")
public class GlobalExceptionController implements ErrorController {

    /**
     * 错误信息的构建工具.
     */
    @Autowired
    private GlobalExceptionResolver globalExceptionResolver;

    /**
     * 错误信息页的路径
     */
    private final static String DEFAULT_ERROR_VIEW = "error";

    /**
     * 获取错误控制器的映射路径.
     */
    @Override
    public String getErrorPath() {
        return globalExceptionResolver.getErrorProperties().getPath();
    }

    /**
     * 情况1：若预期返回类型为text/html,s则返回错误信息页(View).
     */
    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public ModelAndView errorHtml(HttpServletRequest request) {
        return new ModelAndView(DEFAULT_ERROR_VIEW,
                "ExceptionInfo", globalExceptionResolver.getExceptionInfo(request));
    }
    /**
     * 情况2：其它预期类型 则返回详细的错误信息(JSON).
     */
    @RequestMapping
    @ResponseBody
    public ExceptionInfo error(HttpServletRequest request) {
        return globalExceptionResolver.getExceptionInfo(request);
    }
}
